import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from 'components/login/Login'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: () => import ('components/home/Home'),// 懒加载
    redirect: '/welcome',
    children: [
      /* 欢迎首页 */
      {path: '/welcome', name: 'welcome', component: () => import ('views/welcome/Welcome')},
      /* 用户管理 */
      {path: '/users', name: 'users', component: () => import ('views/user/User')},
      /* 权限管理 */
      {path: '/roles', name: 'roles', component: () => import ('views/power/Roles')},
      {path: '/rights', name: 'rights', component: () => import ('views/power/Rights')},
      /* 商品管理 */
      {path: '/goods', name: 'goods', component: () => import('views/goods/Goods')},
      {path: '/params', name: 'params', component: () => import('views/goods/Params')},
      {path: '/categories', name: 'categories', component: () => import ('views/goods/Categories')},
      /* 订单管理 */
      {path: '/orders', name: 'orders', component: () => import ('views/order/Orders')},
      /* 数据统计 */
      {path: '/reports', name: 'reports', component: () => import ('views/report/Reports')},
    ]
  }
]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

/**
 * 挂载路由导航守卫
 * to 将要访问的路径
 * from 代表从那个路径跳转而来
 * next 是一个函数，表示放行
 */
router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页，直接放行
  if (to.path === '/login') return next();
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token');
  // 判断token是否存在，如果不存在直接跳转到登录界面
  if (!tokenStr) return next('/login');
  // 跳转到下一个界面
  next()

})


export default router
